<template>
	<van-popup v-model:show="popupShow" round closeable position="bottom" :style="{ height: '92%' }" class="sku-popup" @click-close-icon="resetSelected" @click-overlay="resetSelected">
		<div class="header-wrap">
			<div class="flex">
				<div class="price font-14" v-if="gdsSku.minAgentPrice>0">
					<template v-if="gdsSku.minGuidePrice===gdsSku.maxGuidePrice"><small>￥</small>{{fen2Yuan(gdsSku.minGuidePrice)}}</template>
					<template v-else><small>￥</small>{{fen2Yuan(gdsSku.minGuidePrice)}} ~ <small>￥</small>{{fen2Yuan(gdsSku.maxGuidePrice)}}</template>
				</div>
				<div class="price txt-primary" v-else>
					<template v-if="gdsSku.minGuidePrice===gdsSku.maxGuidePrice"><small>￥</small><span>{{fen2Yuan(gdsSku.minGuidePrice)}}</span></template>
					<template v-else><small>￥</small><span>{{fen2Yuan(gdsSku.minGuidePrice)}}</span> <span class="range">~</span> <small>￥</small><span>{{fen2Yuan(gdsSku.maxGuidePrice)}}</span></template>
				</div>
				<van-tag plain class="tag">指导价</van-tag>
			</div>
			<div class="flex" v-if="gdsSku.minAgentPrice>0 && gdsSku.priceLadders.length===0">
				<div class="price price-normal">
					<template v-if="gdsSku.minGuidePrice===gdsSku.maxGuidePrice"><small>￥</small><span>{{fen2Yuan(gdsSku.minAgentPrice)}}</span></template>
					<template v-else><small>￥</small><span>{{fen2Yuan(gdsSku.minAgentPrice)}}</span> <span class="range">~</span> <small>￥</small><span>{{fen2Yuan(gdsSku.maxAgentPrice)}}</span></template>
				</div>
<!--				<van-tag plain type="primary" class="tag">提货价</van-tag>-->
				<span v-if="minBuyCount>1" class="txt-gray font-12 mgl10">{{minBuyCount}}件起批</span>
			</div>
			<div class="ladder-wrap" v-if="gdsSku.priceLadders&&gdsSku.priceLadders.length>0">
				<div class="ladder-wrap-bg"/>
				<div class="block" v-for="(ladder,index) in gdsSku.priceLadders" key="index" :class="ladderMeetIndex===index?'is-meet':''">
					<div class="price-ladder"><small>￥</small><span>{{fen2Yuan(ladder.afterAmountPrice)}}</span></div>
					<div class="num-range" v-if="ladder.buyMaxAmount>0">{{ladder.buyMinAmount}}~{{ladder.buyMaxAmount}}件</div>
					<div class="num-range" v-else>≥{{ladder.buyMinAmount}}件</div>
				</div>
			</div>
		</div>
		<div class="main-sku-wrap">
			<van-cell-group inset>
				<div class="prop-row" v-if="gdsSku.props&&gdsSku.props.length>1">
					<label>{{gdsSku.props[0].propValue}}</label>
					<ul class="options-wrap">
						<li v-for="(pt,index) in skuGroup.groupList" key="pt.vId" @click="onFirstLevelPropSelected(pt.vId,pt.vName)" :class="pt.vId===propTabActive? 'active':''">
							<van-badge :content="pt.selectNum" :show-zero="false">
								<van-icon v-if="pt.vImg" class="btn-preview" name="expand-o" @click.stop="imgPreview(pt.vImg)"/>
								<img v-if="pt.vImg" alt="" :src="pt.vImg"/><div class="sku-value">{{pt.vName}}</div>
							</van-badge>
						</li>
					</ul>
				</div>
				<label class="mgl10">{{gdsSku.props[gdsSku.props.length-1].propValue}}</label>
				<template v-if="gdsSku.props&&gdsSku.props.length>0">

					<div class="list-wrap" v-for="group in skuGroup.groupList" key="group.vId" v-show="group.vId===propTabActive">
						<van-cell v-for="item in group.skuList">
							<template #title>
								<van-badge v-if="item.skuImg" :content="item.selectNum" :show-zero="false">
									<img alt="" :src="item.skuImg" @click="imgPreview(item.skuImg)"/>
								</van-badge>
								<van-badge v-else :content="item.selectNum" :show-zero="false"/>
								<div class="col-main">
									<div>
										<template v-for="(para,index) in item.params" key="para.vId">
											<span v-if="index>0" class="pre">&middot;</span>
											<b>{{para.vName}}</b>
										</template>
									</div>
									<div class="sec-floor">
										￥{{skuPrice(item.skuPrice)}} <span class="mgr5 mgl5">|</span>
										<template v-if="item.stockAmount>0">库存{{item.stockAmount}}</template>
										<template v-else>缺货</template>
									</div>
								</div>
							</template>
							<van-stepper :disabled="!item.stockAmount||item.stockAmount===0" integer :default-value="0" input-width="1rem"
										 v-model="item.selectNum" :min="0" :max="item.stockAmount" @change="handleChange" />
						</van-cell>
					</div>
				</template>
			</van-cell-group>
		</div>
		<div class="sheet-stat">
			<div>已选 <span class="txt-primary">{{totalCount}}</span> 件</div>
			<div>总额(不含运费)：<span class="txt-primary">￥<span class="font-16">{{totalPrice}}</span></span></div>
		</div>
		<div class="sheet-btn-wrap">
			<van-button type="warning" v-if="btnCartShow" :disabled="actionDisable" @click="handleAddCartClick">加采购车</van-button>
			<van-button type="primary" v-if="btnBugShow" :disabled="actionDisable" @click="handleBuyClick">立即订购</van-button>
		</div>
	</van-popup>
</template>
<style lang="scss" scoped>
.header-wrap{
	padding:10px 16px;border-bottom:1px solid var(--van-cell-border-color);
	--van-tag-primary-color:var(--van-primary-color);
	.tag{margin-left:4px;padding:0 3px;}
	&>.flex{
		height:24px;
		&:first-child{margin-top:6px;}
	}
	.price{
		height:24px;line-height:24px;
	}
	small{font-family: Helvetica;font-size:60%;}
	.price-normal{
		color:var(--van-primary-color);
		span{display:inline-block;font-size:20px;line-height: 24px;height:24px;font-weight:bold}
		del{margin-left: 5px; color:var(--font-placeholder-color); font-size: 16px;}
		.range{font-size:12px;font-family: Tahoma;}
	}
	.ladder-wrap{
		height:40px;display:flex; align-items: stretch;
		.block{
			flex:1;text-align: center;position:relative;padding:3px 0; border-radius:8px;
			&.is-meet{background:rgba(0,0,0,.08)}
		}
		.price-ladder{
			color:var(--van-primary-color);
			span{display:inline-block;font-size:18px;line-height:20px;height:20px;}
			small{ font-family: Helvetica;font-size:12px;}
		}
		.num-range{
			line-height:14px;height:14px;font-size:12px; color:var(--font-second-color);
		}
	}
}
.sheet-btn-wrap{
	.van-button{border-radius:0;font-weight:bold;display:block;flex:1;}
	:deep(.van-button--primary){
		background: linear-gradient(90deg, #fff -250%, var(--van-primary-color) 100%);
	}
	:deep(.van-button--warning){
		background: var(--van-action-bar-button-warning-color);
	}
	.van-button:first-child{
		border-top-left-radius: 22px;border-bottom-left-radius: 22px;
	}
	.van-button:last-child{
		border-top-right-radius: 22px;border-bottom-right-radius: 22px;
	}
}
.sheet-stat{
	height:33px;background: var(--white-color);display:flex;align-items: center; justify-content: space-between;
	border-top:1px solid var(--van-cell-border-color); font-size:12px;
	position:absolute;bottom:calc(50px + env(safe-area-inset-bottom)); left:0;right:0;padding:4px 16px 0;
	&>div:first-child{ color:var(--font-third-color);}
}
.main-sku-wrap{
	max-height:v-bind(mainHeight);overflow-x:hidden; overflow-y:auto;
	label{font-size:14px;font-weight:bold;display:block;margin-bottom:4px;}
	:deep(.van-badge__wrapper){display:block;}
	:deep(.van-badge--top-right){ transform: translate(0,-50%); }
	.prop-row {
		padding: 10px;position:relative;
		&:first-child::after{
			box-sizing:border-box; content: " "; pointer-events: none;display:block;
			border-bottom: 1px solid var(--van-cell-border-color); transform: scaleY(.5);
		}
		.options-wrap {
			flex: 1; margin:0 -6px 0 0; display: flex; flex-wrap: wrap; padding: 0;
			li {
				display: block; margin: 0 6px 6px 0; width:calc((100vw - 58px)/4);
				border-radius: 8px;
				position: relative;
				cursor: pointer;
				background-color: var(--van-image-placeholder-background);
				border: 1px solid var(--border-lighter-color);
				img { width:100%; aspect-ratio: 1;border-radius:7px 7px 0 0; display:block; }
				.sku-value {
					height:28px; display:flex; align-items:center; font-size:12px; padding:0 4px; justify-content:center;
				}

				&.active, &.active:hover {
					border-color: var(--van-primary-color);
					color: var(--van-primary-color);
					background-color: var(--white-color);
					&::before { content: ''; display: block; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: var(--van-primary-color); opacity: .1; }
				}
			}
		}
	}
	.list-wrap {
		:deep(.van-cell__title){
			flex:2.2;line-height:20px; display:flex; align-items:center; font-size:13px; max-height:50px;
		}
		img { width:48px; height:48px;display:block; overflow:hidden; border-radius:4px;}
		.col-main {padding-left:8px;line-height:18px;}
		.pre{margin:0 2px}
		.sec-floor{ font-size:12px; color:var(--font-third-color); }
	}
	.btn-preview{
		display:flex;width:26px;height:26px;background:rgba(0,0,0,.3);align-items:center;justify-content:center;
		color:var(--white-color);font-size:20px;position:absolute; bottom:32px;right:4px; border-radius:4px;
	}
}
</style>
<script lang="ts" setup>
import { showImagePreview } from 'vant'
import {PriceLadderItem, SkuItem, SkuStruct} from "@/types";
import {fen2Yuan} from "@/utils/validate";
//props
const props=defineProps<{
	gdsSku:SkuStruct,
	minBuyCount:Number,
}>()
//emits
const emit = defineEmits<{
	(e: 'add-cart-click', skuSelected: any): void
	(e: 'buy-click', skuSelected: any): void
}>()

//data
const popupShow=ref(false)
const btnCartShow=ref(false)
const btnBugShow=ref(false)
const previewImgList:string[] = []

//首层横列属性默认选中项的vId
const propTabActive=ref('')
//每个初级属性tab下，各有哪些sku单品信息
const skuGroup=reactive<any>({
	propId:'',
	//expendDown:false,
	groupList:<Array<any>>[],
})
const ladders=ref<Array<PriceLadderItem>>([]) //阶梯价设定
const ladderMeetIndex=ref(0) //当前的订购量满足第几档阶梯价默认0，起始档为第0档
const totalCount=ref(0) //已选的单品件数总数
const totalPrice=ref(0) //已选的单品总额

//computed
const mainHeight=computed(()=>{
	if(props.gdsSku.priceLadders&&props.gdsSku.priceLadders.length>0){
		return 'calc(92vh - 174px)'
	}else{
		return 'calc(92vh - 158px)'
	}
})
//计算属性：已选的单品价格显示
const skuPrice = computed(()=>{
	return function(initPrice:number){
		if(!props.gdsSku.priceLadders || props.gdsSku.priceLadders.length===0)	return fen2Yuan(initPrice)
		return fen2Yuan(ladders.value[ladderMeetIndex.value<0? 0:ladderMeetIndex.value].afterAmountPrice)
	}
})

//初始化 begin
const getImgOfSku=(skuParams:{propId: string, propValue: string, vId: string, vName: string}[]|undefined)=>{
	if(!skuParams||skuParams.length===0)	return undefined
	for(let para of skuParams){
		for( let prop of props.gdsSku.props){
			if(prop.propId==para.propId){
				for(let item of prop.params){
					if(item.vId===para.vId){
						return item.vImg||undefined
					}
				}
			}
		}
	}
	return undefined
}
if(props.gdsSku && props.gdsSku.props ){
	//初始化阶梯价
	if(props.gdsSku.priceLadders && props.gdsSku.priceLadders.length>0){
		for(let ladder of props.gdsSku.priceLadders)	ladders.value.push(ladder)
	}
	//初始化常规则单品信息
	let maxLen=0
	if(props.gdsSku.props.length>1){
		propTabActive.value = props.gdsSku.props[0].params[0]?.vId
		skuGroup.propId=props.gdsSku.props[0].propId
		for(let pt of props.gdsSku.props[0].params){
			if(pt.vImg){
				previewImgList.push(pt.vImg)//把可能的sku图片抽出来，加入图片预览列表中
			}
			let group={
				vId:pt.vId,
				vName:pt.vName,
				vImg:pt.vImg||undefined,
				skuList:<SkuItem[]>[],
				selectNum:0,
				//selectMoney:0,
			}
			for(let item of props.gdsSku.skus){
				const para = item.params?.find( (it:any)=> {return it.propId =skuGroup.propId})
				if(para&&para.vId===group.vId){
					//加入到列中
					group.skuList.push({
						gdsId: item.gdsId,
						skuId: item.skuId,
						skuPrice: item.skuPrice,
						stockAmount: item.stockAmount,
						params: item.params?.filter(it=>it.propId!==skuGroup.propId),
						selectNum:0,
					})
				}
			}
			// console.log(group.skuList)
			skuGroup.groupList.push(group)
			if(group.skuList.length>maxLen){ maxLen=group.skuList.length }
		}
	}else{
		let group={
			vId:'',
			vName:'',
			vImg:undefined,
			skuList:<SkuItem[]>[],
			selectNum:0,
			//selectMoney:0,
		}
		for(let item of props.gdsSku.skus){
			//加入到列中,仅这里才需要读取单品的图片
			let vImg = getImgOfSku(item.params)
			if(vImg)previewImgList.push(vImg)//把可能的sku图片抽出来，加入图片预览列表中
			group.skuList.push({
				gdsId: item.gdsId,
				skuId: item.skuId,
				skuPrice: item.skuPrice,
				stockAmount: item.stockAmount,
				params: item.params, selectNum:0,
				skuImg: vImg //仅当属性只有一层时，才有必要在纵向列表中显示可能存在的单品图片
			})
		}
		skuGroup.groupList.push(group)
		if(group.skuList.length>maxLen){ maxLen=group.skuList.length }
	}
	// if(maxLen<4){
	// 	skuGroup.expendDown=true
	// }
}
//初始化 end

//computed
const actionDisable=computed(()=>{
	return totalCount.value===0||totalCount.value<props.minBuyCount
})

//methods
const displaySkuSheet =(type:string|undefined)=>{
	popupShow.value=true
	if(!type){
		btnCartShow.value=true
		btnBugShow.value=true
	}else if('0'===type){
		btnCartShow.value=true
		btnBugShow.value=false
	}else{
		btnCartShow.value=false
		btnBugShow.value=true
	}
}
const hideSkuSheet =()=>{popupShow.value=false}

//重置清空当前sku弹框里的选择
const resetSelected=()=>{
	for(const group of skuGroup.groupList){
		for(const item of group.skuList){
			item.selectNum=0
		}
	}
	if(skuGroup.groupList.length>0)
		propTabActive.value = skuGroup.groupList[0].vId
}


//单品选择数量改变的事件
const handleChange = () => {
	//console.log(cur)
	let allCount=0,allPrice=0
	for(let group of skuGroup.groupList){
		let numSelect=0,moneySelect=0
		for(let sku of group.skuList as any[]){
			numSelect += sku.selectNum as number
			moneySelect += sku.skuPrice*sku.selectNum
		}
		group.selectNum = numSelect
		allCount += numSelect
		allPrice += moneySelect
	}
	//如果使用了阶梯价，则对总价进行再次计算
	if(ladders.value.length>0){
		allPrice=0;
		let meetIt = ladders.value.findIndex(item=>(item.buyMinAmount<=allCount&&(item.buyMaxAmount>=allCount||item.buyMaxAmount===0)))
		if(meetIt>-1){
			let meetItem = ladders.value[meetIt]
			allPrice = (meetItem?.afterAmountPrice||0)*allCount
		}
		ladderMeetIndex.value=meetIt
	}
	totalCount.value=allCount
	totalPrice.value=fen2Yuan(allPrice)
}

//首层props列属性被选中时的事件
const onFirstLevelPropSelected=(vId:string,vName?:string)=>{
	propTabActive.value=vId
	//console.log('onFirstLevelPropSelected',' vId='+vId+' vName='+vName)
}
//sku图片预览
const imgPreview=(vImg:string)=>{
	let index = previewImgList.findIndex((item)=> item===vImg)
	//console.log(previewImgList,index)
	if(index>-1){
		showImagePreview({
			images: previewImgList, startPosition: index,
		});
	}
}
//将已挑选的所有sku信息提取出来
const getSkuSelected=()=>{
	let skuSelected={
		totalCount: totalCount.value,
		totalPrice: totalPrice.value,
		skus:<any[]>[],
	}
	for(let group of skuGroup.groupList) {
		for (let sku of group.skuList as any[]) {
			if(sku.selectNum>0){
				skuSelected.skus.push(Object.assign({},sku))
			}
		}
	}
	return skuSelected
}

//加采购车按钮被点击时的事件
const handleAddCartClick=()=>{
	popupShow.value=false
	emit('add-cart-click',getSkuSelected())
	resetSelected()
}
//订购按钮被点击时的事件
const handleBuyClick=()=>{
	popupShow.value=false
	emit('buy-click',getSkuSelected())
	resetSelected()
}

defineExpose({
	//data
	totalCount,totalPrice,ladderMeetIndex,
	//methods
	displaySkuSheet,hideSkuSheet,resetSelected,
})
</script>